/**
 * Class to configure the shader program
 */

/**
 * Constructor
 * @param gl
 * @param shaderProgram
 * @param width
 * @param height
 */
ns.ShaderManager = function(gl, shaderProgram, width, height){
	this.gl = gl;
	this.shaderProgram = shaderProgram;
	this.width = width;
	this.height = height;
	
	this.vertexPositionAttribute = null;
	this.pMatrixUniform = null;
	this.mvMatrixUniform = null;
	
	this.mvMatrix = mat4.create();
	this.pMatrix = mat4.create();
	
	this.triangleVertexPositionBuffer = null;
};

/**
 * Initializes the openGL attributes
 */
ns.ShaderManager.prototype._initGLattributes = function(){
	this.gl.clearColor(0.0, 0.0, 0.0, 1.0);
    this.gl.enable(this.gl.DEPTH_TEST);
};

/**
 * Initializes the attributes' locations in the shader program
 */
ns.ShaderManager.prototype._initAttributeLocation = function(){
	this.vertexPositionAttribute = 
		this.gl.getAttribLocation(this.shaderProgram, "aVertexPosition");
	this.pMatrixUniform =
		this.gl.getUniformLocation(this.shaderProgram, "uPMatrix");
	this.mvMatrixUniform =
		this.gl.getUniformLocation(this.shaderProgram, "uMVMatrix");
};

/**
 * Initializes the shader program
 */
ns.ShaderManager.prototype.init = function(){
	this._initGLattributes();
    
	this._initAttributeLocation();
	
	this.gl.enableVertexAttribArray(this.vertexPositionAttribute);
};

/**
 * Initializes the buffer with the provided vertices
 * @param vertices
 */
ns.ShaderManager.prototype.initBuffer = function(vertices){
	this.triangleVertexPositionBuffer = this.gl.createBuffer();
	this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.triangleVertexPositionBuffer);
    
	this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(vertices),
			this.gl.STATIC_DRAW);
	this.triangleVertexPositionBuffer.itemSize = 3;
	this.triangleVertexPositionBuffer.numItems = 3;
};

/**
 * Draws the scene
 */
ns.ShaderManager.prototype.drawScene = function(){
	this.gl.viewport(0, 0, this.width, this.height);
	this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);

    mat4.perspective(45, this.width / this.height, 0.1, 100.0, this.pMatrix);

    mat4.identity(this.mvMatrix);

    mat4.translate(this.mvMatrix, [-1.5, 0.0, -7.0]);
    this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.triangleVertexPositionBuffer);
    this.gl.vertexAttribPointer(this.vertexPositionAttribute,
    		this.triangleVertexPositionBuffer.itemSize, this.gl.FLOAT,
    		false, 0, 0);
    
    this.gl.uniformMatrix4fv(this.pMatrixUniform, false, this.pMatrix);
	this.gl.uniformMatrix4fv(this.mvMatrixUniform, false, this.mvMatrix);
    
	this.gl.drawArrays(this.gl.LINE_STRIP, 0, this.triangleVertexPositionBuffer.numItems);
};